/********************************************/
/* fragment shader */

precision mediump float;

uniform vec3 uLightLocation;

uniform mat4 uMatrix; 

uniform vec3 uCamera;
varying vec3 vPosition;
varying vec3 vNormal;

uniform sampler2D sTexture;
varying vec2 vTexCoord;

uniform int uLightOff;

void pointLight(
    in vec3 normal,
    inout vec4 ambient,
    inout vec4 diffuse,
    inout vec4 specular,
    in vec3 lightLocation,
    in vec4 lightAmbient,
    in vec4 lightDiffuse,
    in vec4 lightSpecular
) {
	
	mat4 uMMatrix = uMatrix;
	vec3 newPos = (uMMatrix*vec4(vPosition,1)).xyz;
	ambient = lightAmbient;
    vec3 normalTarget = vPosition+normal;
    vec3 newNormal = (uMMatrix*vec4(normalTarget,1)).xyz - (uMMatrix*vec4(vPosition,1)).xyz;
    newNormal = normalize(newNormal);
    
    vec3 eye = normalize( uCamera - newPos );
    vec3 vp = normalize( lightLocation - newPos );
    
    float nDotViewPosition = max(0.0, dot(newNormal, vp));
    diffuse = lightDiffuse*nDotViewPosition;
    
    vec3 halfVector = normalize( vp+eye );
    float shininess=300.0;
    float nDotViewHalfVector = max(0.0, dot(newNormal, halfVector));
    float powerFactor = max( 0.0, pow(nDotViewHalfVector, shininess) );
    specular = lightSpecular*powerFactor;
    //specular = vec4(newNormal,1);
}


void main()
{    
    vec3 color = vec3(0.4,0.1,0.3); 
    vec4 finalColor = vec4(color,1);
    finalColor = texture2D( sTexture, vTexCoord);
    //finalColor = vec4(vTexCoord, 0, 0);
    
    vec4 ambient, diffuse, specular;
    
	pointLight( normalize(vNormal),  ambient, diffuse, specular, uLightLocation, 
		vec4(0.15, 0.15, 0.15, 1.0), vec4(0.8,0.8,0.8,1.0), vec4(1., 1., 1., 1.0) );

	if(uLightOff==0)
		finalColor = finalColor*ambient+ finalColor*diffuse + finalColor*specular;

    gl_FragColor = finalColor;
}

